import 'dart:convert';
import 'dart:math';

import 'package:chathouse/model/hot_service.dart';
import 'package:chathouse/pages/expert/buyWallet/recharge_bank_card.dart';
import 'package:chathouse/pages/expert/buyWallet/wallet_cer_feedback_type.dart';
import 'package:chathouse/util/base_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:chathouse/public/Config.dart';
import 'package:image_picker/image_picker.dart';
import '../../../constant/app_constant.dart';
import '../../../model/wallet_cel.dart';
import '../../base/base.dart';
import '../expert_root_page.dart';

// ignore: must_be_immutable
class WalletCerDetail extends BaseStatefulWidget {
  CerItem? item;
  String imageUrl = "";

  WalletCerDetail(this.item, {Key? key}) : super(key: key);

  @override
  // ignore: no_logic_in_create_state
  _WalletCerDetailState createState() => _WalletCerDetailState(item);
}

class _WalletCerDetailState extends BaseStatefulWidgetState<WalletCerDetail> {
  CerItem? item;
  String imageUrl = "";
  num version = 0;
  String isHaveImg = "";

  _WalletCerDetailState(this.item);

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setState(() {
      updateState(LoadState.success);
    });
    imageUrl = item?.imgPath ?? "";
    isHaveImg = item?.imgPath ?? "";
    version = item?.version ?? 0;
    setState(() {});
    loadInfo();
  }

  void approvalRecharge() {
    if (imageUrl.isEmpty) {
      return;
    }
    final map = {
      "id": item?.id,
      "imgPath": imageUrl,
      "accountNumber": SpUtil.getString(AppConstant.accountNumber),
      "bankName": SpUtil.getString(AppConstant.bankName),
      "tradingCode": Random().nextInt(100000),
      "money": item?.money,
      "serviceContent": item?.serviceContent,
      "version": version,
    };
    Obj.showLoading();
    Apis.approvalRecharge(map)
        .then((value) => {
              Obj.dismissLoading(),
              // ToastUtil.showToast("提交憑證成功,等待審核"),
              showSuccessMsg(),

            })
        .onError((error, stackTrace) => {Obj.dismissLoading()});
  }

  showSuccessMsg() {
    showDialog(
        context: context,
        barrierColor: Colors.black54,
        builder: (BuildContext context) {
          return Container(
            child: Center(
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 20.w, horizontal: 20.w),
                width: 358.w,
                height: 310.w,
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(Styles.magin_40)),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text("發送成功！系統將在2-7個工作天内進行驗證，驗證 通過將自動發放代幣。 請留意提示訊息！",
                        textAlign: TextAlign.center,
                        style: getTextStyle(29.sp,
                            fontType: FontType.MID, color: Styles.c_191919)),
                    SizedBox(
                      height: 40.w,
                    ),
                    Container(
                      alignment: Alignment.center,
                      width: 164.w,
                      height: 54.w,
                      decoration: BoxDecoration(
                          color: Styles.mainColor,
                          borderRadius: BorderRadius.circular(Styles.magin_18)),
                      child: Text(
                        "知道了",
                        style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.w500,
                            fontSize: 24.w),
                      ),
                    ).setOnClickListener(() {
                      Future.delayed(const Duration(seconds: 1), () {
                        Get.offAll(const ExpertRootPage());
                      });
                    })
                  ],
                ),
              ),
            ),
          );
        });
  }

  void loadInfo() {
    Apis.cerDetail(item?.id.toString() ?? "")
        .then((response) => {
              Obj.dismissLoading(),
              setState(() {
                var data = response?.data;
              })
            })
        .onError((error, stackTrace) => {
              Obj.dismissLoading(),
            });
  }

  void onAddImage() async {
    int type = await Get.bottomSheet(Container(
      width: 1.sw,
      height: 120.w,
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(8.w), topRight: Radius.circular(8.w))),
      child: Column(
        children: [
          Text(
            "從相冊中選取",
            style: getTextStyle(18.sp, color: Colors.black),
          )
              .setContainer(
                  width: double.infinity,
                  height: 60.w,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      border: Border(
                          bottom: BorderSide(
                              width: 1.0.w, color: MyColors.gary_149149149))))
              .setOnClickListener(() {
            Get.back(result: 1);
          }),
          Text(
            "相機",
            style: getTextStyle(18.sp, color: Colors.black),
          )
              .setContainer(
            alignment: Alignment.center,
            width: double.infinity,
            height: 60.w,
          )
              .setOnClickListener(() {
            Get.back(result: 2);
          }),
        ],
      ),
    ));
    final ImagePicker picker = ImagePicker();
    final XFile? image = await picker.pickImage(
        source: type == 1 ? ImageSource.gallery : ImageSource.camera);
    var imgData = await image?.readAsBytes();
    Obj.showLoading();
    Map result;
    String? url;
    Apis.uploadFile(imgData!, image?.name ?? "image.png")
        .then((response) => {
              Obj.dismissLoading(),
              debugPrint("upload=${response?.data.toString()}"),
              result = jsonDecode(response?.data ?? ""),
              url = result["url"],
              if (url != null)
                {
                  setState(() {
                    imageUrl = url!;
                  }),
                }
            })
        .catchError((error) => {Obj.dismissLoading(), setState(() {})});
  }

  Widget info() {
    String name = "";
    Color nameColor = Styles.c_191919;
    // ignore: unrelated_type_equality_checks
    if (item?.serviceState == "0") {
      // name = "待验证";
      name = "待驗證";
      nameColor = Styles.c_FF9090;
    }
    // ignore: unrelated_type_equality_checks
    if (item?.serviceState == "1") {
      name = "充值成功";
    }
    // ignore: unrelated_type_equality_checks
    if (item?.serviceState == "2") {
      // name = "充值失败";
      name = "充值失敗";
      nameColor = Styles.color_F93A4A;
    }
    return Column(children: [
      Container(
        decoration: const BoxDecoration(
          color: Colors.white,
        ),
        child: Padding(
          padding: const EdgeInsetsDirectional.fromSTEB(16, 16, 16, 16),
          child: Column(
            children: [
              // SizedBox(height: 24.w),
              Row(
                children: [
                  Text(
                    "訂 單 號    :",
                    style: getTextStyle(18.sp,
                        color: Colors.black, fontType: FontType.BOLD),
                  ),
                  SizedBox(width: 8.w),
                  Text(
                    item?.tradingCode ?? "",
                    style: getTextStyle(18.sp,
                        color: Colors.black, fontType: FontType.BOLD),
                  )
                ],
              ),
              SizedBox(height: 16.w),
              Row(
                children: [
                  Text(
                    "服務内容  :",
                    style: getTextStyle(18.sp,
                        color: Colors.black, fontType: FontType.BOLD),
                  ),
                  SizedBox(width: 8.w),
                  Text(
                    item?.serviceContent ?? '',
                    style: getTextStyle(18.sp,
                        color: Colors.black, fontType: FontType.BOLD),
                  )
                ],
              ),
              SizedBox(height: 16.w),
              Row(
                children: [
                  Text(
                    "充值金額  :",
                    style: getTextStyle(18.sp,
                        color: Colors.black, fontType: FontType.BOLD),
                  ),
                  SizedBox(width: 8.w),
                  Text(
                    "\$${item?.money}",
                    style: getTextStyle(18.sp,
                        color: Styles.c_191919, fontType: FontType.BOLD),
                  )
                ],
              ),
              SizedBox(height: 16.w),
              Row(
                children: [
                  Text(
                    "充值狀態  :",
                    style: getTextStyle(18.sp,
                        color: Colors.black, fontType: FontType.BOLD),
                  ),
                  SizedBox(width: 8.w),
                  Text(
                    name,
                    style: getTextStyle(18.sp,
                        color: Styles.c_FF9090, fontType: FontType.BOLD),
                  )
                ],
              ),
            ],
          ),
        ),
      ),
      SizedBox(height: 16.w),
      item?.serviceState == "2"
          ? Row(
              children: [
                Text(
                  "失敗原因  :",
                  style: getTextStyle(18.sp,
                      color: Colors.black, fontType: FontType.BOLD),
                ),
                SizedBox(width: 8.w),
                Text(
                  item?.feedbackDes ?? "",
                  style: getTextStyle(18.sp,
                      color: Styles.color_F93A4A, fontType: FontType.BOLD),
                )
              ],
            )
          : Container(),
    ]);
  }

  Widget errorInfo() {
    // return
    return Container(
      decoration: const BoxDecoration(
        color: Colors.white,
      ),
      child: Padding(
        padding: const EdgeInsetsDirectional.fromSTEB(16, 16, 16, 16),
        child: Column(
          children: [
            Container(
              alignment: Alignment.centerLeft,
              child: Text(
                "**請安排轉數快FPS 轉帳以上金額至下列轉數快ID 帳號及註明訂單號碼以便跟進. 轉數成功證明可按下到〔我已付款〕上載截圖.",
                textAlign: TextAlign.left,
                style: getTextStyle(18.sp,
                    color: Styles.c_999, fontType: FontType.MID),
              ),
            ),
            SizedBox(height: 16.w),
            Row(
              children: [
                Text(
                  "付款方法  :",
                  style: getTextStyle(18.sp,
                      color: Colors.black, fontType: FontType.BOLD),
                ),
                SizedBox(width: 8.w),
                Text(
                  item?.bankName ?? "",
                  style: getTextStyle(18.sp,
                      color: Colors.black, fontType: FontType.BOLD),
                )
              ],
            ),
            SizedBox(height: 16.w),
            Row(
              children: [
                Text(
                  "轉數快ID.  :",
                  style: getTextStyle(18.sp,
                      color: Colors.black, fontType: FontType.BOLD),
                ),
                SizedBox(width: 8.w),
                Text(
                  item?.accountNumber ?? "",
                  style: getTextStyle(18.sp,
                      color: Colors.black, fontType: FontType.BOLD),
                )
              ],
            ),
            SizedBox(height: 16.w),
            Row(
              children: [
                Text(
                  "交易備註  :",
                  style: getTextStyle(18.sp,
                      color: Colors.black, fontType: FontType.BOLD),
                ),
                SizedBox(width: 8.w),
                Text(
                  " [ 您的訂購號 ]",
                  style: getTextStyle(18.sp,
                      color: Colors.black, fontType: FontType.BOLD),
                )
              ],
            ),
            SizedBox(
              height: 16.w,
            ),
            Container(
              height: 1,
              color: Styles.cf3,
            ),
            SizedBox(
              height: 16.w,
            ),
            Container(
              alignment: Alignment.centerLeft,
              child: Text(
                "*請上傳驗證資料。",
                textAlign: TextAlign.left,
                style: getTextStyle(18.sp,
                    color: Styles.color_F93A4A, fontType: FontType.MID),
              ),
            ),
            SizedBox(
              height: 16.w,
            ),
            Container(
              alignment: Alignment.centerLeft,
              child: Text(
                "*轉數成功後需向我們發送轉數成功截圖以便進行驗證",
                textAlign: TextAlign.left,
                style: getTextStyle(18.sp,
                    color: Styles.c_999, fontType: FontType.MID),
              ),
            ),
            SizedBox(
              height: 16.w,
            ),
            Container(
                alignment: Alignment.centerLeft,
                child: Row(
                  children: [
                    Visibility(
                      visible: imageUrl != "",
                      child: InkWell(
                        child: ImageUtils.image(imageUrl,
                            width: 102.w,
                            height: 102.w,
                            imageType: ImageType.NETWORK,
                            radius: 12),
                      ).setOnClickListener(() {
                        onAddImage();
                      }),
                    ),
                    Visibility(
                      visible: imageUrl != "",
                      child: SizedBox(
                        width: 12.w,
                      ),
                    ),
                    Container(
                      width: 102.w,
                      height: 102.w,
                      decoration: BoxDecoration(
                          color: MyColors.gary_230230230,
                          borderRadius: BorderRadius.circular(20.w)),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          ImageUtils.image(Res.image_pick_add,
                              width: 51.w, height: 51.w),
                          SizedBox(height: 6.w),
                          Text(
                            "選擇照片",
                            style:
                                getTextStyle(16.sp, color: MyColors.brow_25511377),
                          ),
                        ],
                      ),
                    ).setOnClickListener(() {
                      onAddImage();
                    })
                  ],
                )),
            SizedBox(
              height: 16.w,
            ),
            Container(
              height: 1,
              color: Styles.cf3,
            ),
            SizedBox(
              height: 16.w,
            ),
            Text(
              "*您也可以通過以下方法向我們發送入數截圖",
              textAlign: TextAlign.left,
              style:
                  getTextStyle(18.sp, color: Styles.c_999, fontType: FontType.MID),
            ),
            SizedBox(
              height: 20.w,
            ),
            Row(
              children: [
                ImageUtils.image(Res.expert_phone_img, width: 26.w, height: 26.w),
                const SizedBox(
                  width: 6,
                ),
                Text(
                  "WhatsApp:(+852) 5110 9192",
                  textAlign: TextAlign.left,
                  style: getTextStyle(17.sp,
                      color: Styles.c_191919, fontType: FontType.BOLD),
                ),
              ],
            ),
            SizedBox(
              height: 16.w,
            ),
            Row(
              children: [
                ImageUtils.image(Res.expert_email, width: 26.w, height: 20.w),
                const SizedBox(
                  width: 6,
                ),
                Text(
                  "電子郵箱:admin@chathouse.com.hk",
                  textAlign: TextAlign.left,
                  style: getTextStyle(17.sp,
                      color: Styles.c_191919, fontType: FontType.BOLD),
                ),
              ],
            ),
            SizedBox(
              height: 16.w,
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget viewPageBody() {
    return Scaffold(
      appBar: AppBar(
        leading: Icon(
          Icons.arrow_back_ios,
          size: 18.w,
          color: MyColors.gary_149149149,
        ).setOnClickListener(() {
          Get.back();
        }),
        title: Text(
          "充值記錄",
          textAlign: TextAlign.center,
          style:
              getTextStyle(28.sp, color: Colors.black, fontType: FontType.MID),
        ),
        actions: [
          Container(
            padding: const EdgeInsets.only(right: 12),
            child: Center(
              child: Text(
                item?.serviceState == "1" || item?.serviceState == "2"
                    ? "反饋"
                    : (isHaveImg == "")
                        ? "發送"
                        : "重新發送",
                textAlign: TextAlign.center,
                style: getTextStyle(20.sp,
                    color: Styles.mainColor, fontType: FontType.BOLD),
              ),
            ),
          ).setOnClickListener(() {
            if (item?.serviceState == "1" || item?.serviceState == "2") {
              Get.to(WalletCerfeedBackType(
                  item?.id.toString() ?? "", item?.version?.toString() ?? ""));
            } else {
              approvalRecharge();
            }
            // cerList();
          })
        ],
      ),
      body: SafeArea(
        child: Stack(
          children: [
            Container(
              decoration: const BoxDecoration(
                  color: CupertinoColors.systemGrey5,
              ),
              child: ListView(
                // padding: EdgeInsets.symmetric(horizontal: 24.w),
                children: [
                  info(),
                  item?.serviceState == "0" ? errorInfo() : Container()
                ],
              ),
            ),
            Container(
              height: 1,
              decoration: const BoxDecoration(
                color: CupertinoColors.systemGrey4,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
